/**
 * Created by lwy on 2017/6/14.
 */

(function(win){

    var _modifyItemCount = function(merchantId, itemId, count){
        var cartObj = _getCart(merchantId) || {};
        var item = cartObj[itemId];
        if(item){
            count = parseInt(item.count) + count;
            item.count = count > 0 ? count : 0;
            _saveCart(merchantId, cartObj);
        }
    };

    var _len = function(obj){
        var size = 0;
        if(obj){
            for(var key in obj){
                obj.hasOwnProperty(key) && size++;
                //obj.hasOwnProperty(key) &&	(size += obj[key].count);
            }
        }
        return size;
    };


    var _getCart = function(merchantId){
        var cartStr = getCookie('shop_cart_' + merchantId, decodeURIComponent);
        return cartStr && JSONUtil.parse(cartStr);
    };

    var _saveCart = function(merchantId, cartObj){
        var cartStr = JSONUtil.stringify(cartObj);
        setCookie('shop_cart_'+ merchantId, cartStr, 86400, encodeURIComponent);
    };

    win.order = {
        clearCart : function(merchantId){
            _saveCart(merchantId, {});
        },

        //设置物品数量
        setItemCount : function(merchantId, itemId, count){
            count = parseInt(count) || 0;
            var cartObj = _getCart(merchantId) || {};
            var item = cartObj[itemId];
            if(item){
                item.count = count > 0 ? count : 0;
                _saveCart(merchantId, cartObj);
            }
        },

        //获取物品数量
        getItemCount : function(merchantId, itemId){
            var cartObj = _getCart(merchantId) || {};
            var item = cartObj[itemId];
            if(item){
                return item.count;
            }
            return 0;
        },
        //增加物品数量
        incrItemCount: function(merchantId, itemId, count){
            _modifyItemCount(merchantId, itemId, parseInt(count)|| 1);
        },
        //减少物品数量
        decrItem : function(merchantId, itemId, count){
            _modifyItemCount(merchantId, itemId, -1 * parseInt(count) || -1);
        },
        //计算商品总价值
        getTotal : function(merchantId){
            var cartObj =  _getCart(merchantId) || {};
            var total = 0;
            for(var key in cartObj){
                if(cartObj.hasOwnProperty(key) ){
                    total += parseFloat(cartObj[key].price) *  parseInt(cartObj[key].count);
                }
            }
            return total;
        },
    };

})(window);
